/*
2015-8-16
by shadow
jsbase是一个js扩展库，可兼容ie5
 */
(function init(_config) {
	
	// 兼容老IE版本的QuerySelectorAll
	if (!document.querySelectorAll) {
	    document.querySelectorAll = function (selectors) {
	        var style = document.createElement('style'), elements = [], element;
	        document.documentElement.firstChild.appendChild(style);
	        document._qsa = [];

	        style.styleSheet.cssText = selectors +
	         '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
	        window.scrollBy(0, 0);
	        style.parentNode.removeChild(style);

	        while (document._qsa.length) {
	            element = document._qsa.shift();
	            element.style.removeAttribute('x-qsa');
	            elements.push(element);
	        }
	        document._qsa = null;
	        return elements;
	    };
	}

	// 对象复制函数
	function copy(src, dest) {
		dest = dest || window;
		for(var key in src) {
			dest[key] = src[key];
		}
	};
	
	// 转化为数组
	function toArray(obj) {
		return [].slice.apply(obj);
	}
	
	// 对象转化为字符串
	function analyze(object, options) {

	    var resultString;
	    options = options || {};

	    var delimiter = options.delimiter || "&";
	    var delimiter2 = options.delimiter2 || "=";

	    var encodeMode = true;
	    if(options.encode == undefined) {
	        encodeMode = true;
	    }
	    var prefix = options.prefix || "";
	    var members = new Array();

	    for(var key in object) {
	        var value = object[key];
	        if(encodeMode == true) {
	            value = window.encodeURIComponent(value);
	        }
	        var curStr = key + delimiter2 + value;
	        members.push(curStr);
	    }
	    resultString = members.join(delimiter);

	    return resultString;;
	}	
	
	// 格式化文本输出
	function format(string) {

		var args = arguments;

		for(var i = 1; i < args.length; i++) {
			string = string.replace(new RegExp("%" + (i-1), "g"), args[i]);
		}

		return string;
	}	

	// 代码配置
	var config = 
	{
		useSymbol: "$"
	};
	copy(_config, config);

	isOldIE = window["addEventListener"] ? false : true;
	isFF = /firefox/i.test(navigator.userAgent);

	var supportAddEventListener = !isOldIE  ? "addEventListener" : "attachEvent";
	var eventPrefix = !isOldIE ? "" : "on";
	
	// 选择器
	var $ = function(unknown, context) {
		if(typeof(unknown) == "string") {	
			context = context || document;		
			var list = context.querySelectorAll(unknown);
			copy(nodelistExt, list);
			return list;
		}
		else if(unknown.nodeType == 1) {
			var array = [unknown];
			copy(nodelistExt, array);
			return array;
		}
		else {
			window[supportAddEventListener](eventPrefix + "load", unknown);
		}
	};
	
	window[config["useSymbol"]] = $;

	// 代码初始化
	$(function(e) {
		body = document.body;
	});

	// 类型检测函数
	function und(obj) {
		return (obj == undefined);
	};

	function str(obj) {
		return (typeof(obj) == "string");
	};

	function obj(obj) {
		return (typeof(obj) == "object");
	};
	
	function fun(obj) {
		return (typeof(obj) == "function");
	};
	
	function boo(obj) {
		return (typeof(obj) == "boolean");
	};

	function arr(obj) {
		return (obj instanceof Array);
	};

	function empty(obj) {
		return (obj == null) || (obj == undefined) || (obj == "") || (obj.length == 0);
	};

	// 元素创建函数
	element = function(tagName, innerHTML, className, id) {
		var node = document.createElement(tagName);

		if(!empty(innerHTML)) {
			node.innerHTML = innerHTML;
		}
		if(!empty(className)) {
			node.className = className;
		}
		if(!empty(id)) {
			node.id = id;
		}
		return node;
	}	

	function fragment() {
		return document.createDocumentFragment();
	}

	var tagMap =
	{
		div: ["innerHTML", "className", "id"],
		p: ["innerHTML", "className", "id"],
		img: ["src", "className", "id"],
		a: ["href", "innerHTML", "className", "id"]
	}

	for(var tag in tagMap) {
		window[tag] = (function(_tag) {

			return (function() {
				var node = document.createElement(_tag);
				var list = tagMap[_tag];
				for(var i = 0; i < list.length; i++) {
					if(arguments[i] != undefined)
						node[list[i]] = arguments[i];
				}

				return node;
			});
		})(tag);
	}

	// 元素操作声明
	var dom = {};

	dom.on = function() {
		var array = toArray(arguments);
		if(isOldIE) {
			array[0] = "on" + array[0];
		}
		this[supportAddEventListener].apply(this, array);
		return this;
	};
	
	dom.off = function() {
		this.removeEventListener.apply(this, arguments);
		return this;
	};

	dom.css = function(name, value) {
		if(value == undefined) {
			if(isOldIE) {
				return this["currentStyle"][name];
			}
			else {
				return window.getComputedStyle(this)[name];
			}
		}
		else {
			this.style[name] = value;
			return this;
		}
	};

	dom.attr = function(name, value) {
		if(value == undefined) {
			return this.getAttribute(name);
		}
		else {
			this.setAttrbiute(name, value);
			return this;
		}
	};

	dom.html = function(content) {
		this.innerHTML = content;
		return this;
	};

	dom.text = function(content) {
		if(isFF){
			this.textContent = content;
		}
		else {
			this.innerText = content;					
		}
		return this;
	};

	dom.show = function() {
		this.style["display"] = "block";
		return this;
	};

	dom.isShow = function() {
		var value = $(this).css("display");
		return (value != "none");
	};

	dom.hide = function() {
		this.style["display"] = "none";
		return this;		
	};

	dom.toggle = function() {
		if($(this).isShow() == true) {
			$(this).hide();
		}
		else {
			$(this).show();
		}
		return this;
	}

	dom.append = function() {
		this.appendChild.apply(this, arguments);
		return this;
	}

	dom.remove = function() {
		this.parentElement.removeChild(this);
		return this;
	}

	// 节点集合操作函数
	var nodelistExt = {
		each: function(callback) {
			for(var i = 0; i < this.length; i++) {
				var node = this[i];
				callback.call(node, node, i);
			}
		}
	};
	// 使集合可以扩展
	$.listExt = nodelistExt;
	$.addExt = function(name, callback) {
		$.listExt[name] = function() {

			this.each(function(node, index) {
				callback.call(node, node, index);
			});

			return this;
		}
	};

	var nodeMethods = 
	["on", "off", "css", "attr",
	 "show", "hide", "toggle", "isShow",
	 "append", "remove"];

	for(var i=0;i<nodeMethods.length;i++) {
		var method = nodeMethods[i];

		nodelistExt[method] = (function(_method) {
			return function() {
				var nodelist = this;

				for(var iNode=0;iNode < nodelist.length;iNode++) {
					var node = this[iNode];
					var result = dom[_method].apply(node, arguments);
					if(result != node) {
						return result;
					}
				}

			return this;			
		}
		})(method)
	}

	// 网络相关函数
	function http(url, _opts) {
		var request = new XMLHttpRequest();
		var opts = {
			method: "GET",
			async: true,
			data: null
		};
		copy(_opts, opts);

		var method = opts.method.toUpperCase();
		var isAsync = opts.async;
		var data;
		if(typeof(opts.data) == "object") {
			data = analyze(opts.data);
		}
		if(method == "GET") {
			if(data) {
				url += "?";
			}
			url+= data;
			data = null;
		}

		request.open(method, url, isAsync);

		if(method == "POST") {
			request.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		}
		request.send(data);

		if(isAsync) {
			request.onload = function(e) {
				var data = request.responseText;
				try {
					data = JSON.parse(data);
				}
				catch(e) {				
				}
				opts.success &&
				 opts.success.call(e, data, request);
			}
		}

		return request;
	}

	function get(url, data, success) {
		if(typeof(data) == "function") {
			success = data;
			data = null;
		}	
		var opts =
		{
			method: "GET",
			data: data,
			success: success
		};
		return http(url, opts);
	}

	function post(url, data, success) {
		if(typeof(data) == "function") {
			success = data;
			data = null;
		}
		var opts =
		{
			method: "POST",
			data: data,
			success: success
		}
		return http(url, opts);
	}	

	// 模板函数
	// 内置模板
	$.compiles = 
	{
		show: function(dom, expr, data) {
			var result = eval(expr);
			if(!result) {
				dom.style["display"] = "none";
			}
			else {
				dom.style["display"] = "block";
			}
		},
		hide: function(dom, expr, data) {
			var result = eval(expr);
			if(!result) {
				dom.style["display"] = "block";
			}
			else {
				dom.style["display"] = "none";
			}
		},
		if: function(dom, expr, data) {
			var result = eval(expr);
			if(!result) {
				dom.parentNode.removeChild(dom);
			}
		},	

		repeat: function(dom, expr, data, callback) {
			var data = eval(expr);
			var doc = fragment();
			var val;
			if(arr(data)) {
				for(var i=0;i<data.length;i++) {
					val = data[i];
					callback && callback(val, i, data);
					_execute(null, data[i], i);
				}
			}
			else {
				for(var key in data) {
					val = data[key];
					callback(val, key, data);
					_execute(key, val, i++);
				}
			}

			dom.parentNode.insertBefore(doc, dom);
			dom.parentNode.removeChild(dom);

			function _execute(key, value, index) {
				var clone = dom.cloneNode(true);
				clone.removeAttribute("tid");
				var content = clone.innerHTML;
				var matches = content.match(/{([^}]+)}/g) || [];

				for(var j = 0;j < matches.length; j++) {
					var match = matches[j];
					var expr = match.match(/{([^}]+)}/)[1];
					var _value = eval(expr);
					if(und(_value)) {
						_value = "";
					}
					clone.innerHTML = clone.innerHTML.replace(new RegExp(match), _value);
					doc.appendChild(clone);
				}		
			}
		}
	};	

	// 模板编译
	function compile(selector, data, callback) {
		$(selector).each(function(dom) {

			for(var attrName in $.compiles) {
				var execute = $.compiles[attrName];
				var list = $("[" + attrName + "]", dom);
				list.each(function(dom) {
					var expr = dom.getAttribute(attrName);
					execute(dom, expr, data, callback);
				});
			}
		});
	}	

	// 公开成员
	copy({
		copy: copy,
		analyze: analyze,
		format: format,
		toArray: toArray,

		boo: boo,
		str: str,
		fun: fun,
		obj: obj,
		und: und,
		empty: empty,
		arr: arr,

		element: element,
		fragment: fragment,

		
		http: http,
		get: get,
		post: post,

		compile: compile
	}, window);	
})({
	useSymbol: "$"
});